"""Script to blacklist tests with some useragents."""

import os
import sys
from optparse import OptionParser

from browsertests.utils import cli_wrapper
from browsertests.tests.models import Test
from browsertests.tests.models import TestBlacklist
from browsertests.useragents.models import Useragent
from django.db.models import Q
from django.db import connection

def blacklist_tests_for_ua(tests, ua):
    print "Test count:", len(tests)

    for test in tests:
        print "blacklisting ", test, "for ua", ua
        try:
            bl = TestBlacklist.objects.get(test=test, ua=ua)
        except TestBlacklist.DoesNotExist:
            pass
        else:
            print "   (already blacklisted)"
            continue

        bl = TestBlacklist()
        bl.test = test
        bl.ua = ua
        bl.save()

def disable_tests(tests):
    print "Test count:", len(tests)
    for test in tests:
        if not test.enabled:
            print "   (already disabled)"
            continue
        test.enabled = False
        print "disabling ", test
        test.save()


def blacklistsvg(ua):
    svgpath = "reftests/svg"
    tests = Test.objects.filter(Q(file__contains=svgpath) | Q(file2__contains=svgpath) |
                                Q(url__contains="LayoutTests/dom/svg"))
    blacklist_tests_for_ua(tests, ua)

def blacklistxhtml(ua):
    tests = Test.objects.filter(url__endswith=".xhtml")
    blacklist_tests_for_ua(tests, ua)

def blacklistdomtests(ua):
    tests = Test.objects.filter(Q(url__contains="tests/mochitest/dom-level1-core") |
                                Q(url__contains="tests/mochitest/dom-level2-core"))
    blacklist_tests_for_ua(tests, ua)

# Blacklists tests for browsers that do not support toDataURL()
def blacklistcanvastodataurl(ua):
    tests = Test.objects.filter(url__contains="content/canvas/test")
    blacklist_tests_for_ua(tests, ua)

def get_ua(product, branch, platform):
    return Useragent.objects.get_by_pbp(product, branch, platform)

def delete_disabled_browsers_blacklists():
    cursor = connection.cursor()
    cursor.execute(
        """DELETE FROM tests_testblacklist WHERE
            EXISTS (
                SELECT 1
                FROM useragents_useragent ua
                WHERE
                    tests_testblacklist.ua_id = ua.id AND
                    ua.enabled = 0
            )
        """)

def blacklist():
    delete_disabled_browsers_blacklists()

    ie6 = get_ua("IE", "6", "win")
    ie7 = get_ua("IE", "7", "win")
    ie8 = get_ua("IE", "8", "win")
    safari3win = get_ua("Safari", "3", "win")
    safaritrunkwin = get_ua("Safari", "trunk", "win")
    opera9win = get_ua("Opera", "9", "win")
    opera9lin = get_ua("Opera", "9", "lin")

    #ENABLED = False
    ENABLED = True
    ENABLED_ = True

    ################
    # Unsupported features.

    if ENABLED:
        blacklistsvg(ie6)
        blacklistsvg(ie7)
        blacklistsvg(ie8)
        blacklistxhtml(ie6)
        blacklistxhtml(ie7)
        blacklistxhtml(ie8)
        blacklistdomtests(ie6)
        blacklistdomtests(ie7)
        blacklistdomtests(ie8)

    if ENABLED:
        blacklistcanvastodataurl(safari3win)
        blacklistcanvastodataurl(safaritrunkwin)
        blacklistcanvastodataurl(ie7)
        blacklistcanvastodataurl(ie8)


    if ENABLED:
        # no css counters
        blacklist_tests_for_ua(Test.objects.filter(url__contains="mozilla/layout/reftests/counters"),
                               ie6)
        blacklist_tests_for_ua(Test.objects.filter(url__contains="mozilla/layout/reftests/counters"),
                               ie7)

    ################
    # Issues that were investigated.

    # This test confuses Opera and all consecutive tests will fail.
    if ENABLED:
        blacklist_tests_for_ua([Test.objects.get(url="http://localhost:8888/LayoutTests/fast/js/array-indexof.html")],
                               opera9win)

    # no cgi support yet. Disable XHR tests.
    if ENABLED:
        tests = Test.objects.filter(url__contains="tests/xmlhttprequest")
        disable_tests(tests)

    # Opera 9.6 on Windows executes the onload event before all frames are loaded on some tests. Disable them.
    if ENABLED:
        blacklist_tests_for_ua(Test.objects.filter(url__contains="dom-level1-core/test_hc_"),
                               opera9win)

    if ENABLED:
        # These tests fail with "testFinished called without active test" because they need a longer timeout.
        blacklist_tests_for_ua(Test.objects.filter(pk="tests/content/media/video/test/test_bug468190.html"),
                               get_ua("Firefox", "trunk", "lin"))
        blacklist_tests_for_ua(Test.objects.filter(pk="tests/content/media/video/test/test_ended2.html"),
                               get_ua("Firefox", "trunk", "lin"))


    ################
    # Issues that need to be investigated.

    # xpath tests failure with Opera
    if ENABLED:
        blacklist_tests_for_ua(Test.objects.filter(url__contains="LayoutTests/dom/svg/level3/xpath"),
                               opera9lin)
        blacklist_tests_for_ua(Test.objects.filter(url__contains="LayoutTests/dom/svg/level3/xpath"),
                               opera9win)

    # png suite fails with Opera 9.6 Windows, IE, Fx2
    if ENABLED:
        tests = Test.objects.filter(url__contains="reftest/pngsuite")
        blacklist_tests_for_ua(tests, opera9win)
        blacklist_tests_for_ua(tests, ie6)
        blacklist_tests_for_ua(tests, ie7)
        blacklist_tests_for_ua(tests, ie8)
        blacklist_tests_for_ua(tests, safari3win)
        blacklist_tests_for_ua(tests, safaritrunkwin)
        blacklist_tests_for_ua(tests, get_ua("Firefox", "2", "win"))
        blacklist_tests_for_ua(tests, get_ua("Firefox", "2", "lin"))

    # JSON Exception
    if ENABLED:
        json_failures = (
            "LayoutTests/fast/js/regexp-compile-crash.html",
            "LayoutTests/fast/js/regexp-extended-characters-crash.html",
            "LayoutTests/fast/regex/test4.html",
        )
        tests = Test.objects.filter(pk__in=json_failures)
        disable_tests(tests)

    # Requires a proprietary window. method

    if ENABLED:
        disable_tests(Test.objects.filter(pk__startswith="LayoutTests/accessibility/"))

    # JSON Exception
    if ENABLED:
        blacklist_tests_for_ua(Test.objects.filter(pk="LayoutTests/fast/regex/test1.html"), safari3win)
        blacklist_tests_for_ua(Test.objects.filter(pk="LayoutTests/fast/regex/test1.html"), safaritrunkwin)

    # Firefoxen fail the media layouttests
    if ENABLED:
        tests = Test.objects.filter(pk__startswith="LayoutTests/media/")
        disable_tests(tests)

    if ENABLED:
        # IE JSON issues
        blacklist_tests_for_ua(Test.objects.filter(pk="LayoutTests/fast/encoding/utf-32-big-endian-bom.html"), ie6)
        blacklist_tests_for_ua(Test.objects.filter(pk="LayoutTests/fast/encoding/utf-32-big-endian-bom.html"), ie7)
        blacklist_tests_for_ua(Test.objects.filter(pk="LayoutTests/fast/encoding/utf-32-big-endian-bom.html"), ie8)
        # testFinished called without active test
        blacklist_tests_for_ua(Test.objects.filter(pk="tests/dom/tests/mochitest/ajax/mochikit/test_Mochikit.html"), ie6)
        blacklist_tests_for_ua(Test.objects.filter(pk="tests/dom/tests/mochitest/ajax/mochikit/test_Mochikit.html"), ie7)
        blacklist_tests_for_ua(Test.objects.filter(pk="tests/dom/tests/mochitest/ajax/mochikit/test_Mochikit.html"), ie8)

def main():
    from optparse import OptionParser
    usage = "%prog [OPTIONS]"
    parser = OptionParser(usage=usage)

    parser = cli_wrapper.add_common_parser_options(parser)
    options, args = parser.parse_args()

    if len(args) != 0:
        parser.print_help()
        sys.exit(2)

    cli_wrapper.process_options(options)

    blacklist()

if __name__ == "__main__":
    main()
